﻿//---------------------------------------------
//            Tasharen Network
// Copyright © 2012-2013 Tasharen Entertainment
//---------------------------------------------

using System;
using System.IO;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Net;
using System.Threading;

namespace TNet
{
    // 消息基类
    public abstract class MsgBase
    {
        public MsgBase(ushort id)
        {
            ProtocolID = id;
        }

        public ushort ProtocolID; // 协议ID
        public abstract void WriterBinary(BinaryWriter binary); // 写入到二进制当中
        public abstract void ReadByBinary(BinaryReader binary); // 从二进制当中读取数据
    }

    public abstract class CallbackBase
    {
        public abstract void OnEvent(MsgBase obj); // 事件回调

        protected abstract MsgBase Create();

        // 转换为二进制数据
        public Buffer WriterBinary(MsgBase msg)
        {
            Buffer buffer = Buffer.Create(true);
            BinaryWriter binaryWriter = buffer.BeginPacket(msg.ProtocolID);
            msg.WriterBinary(binaryWriter);
            buffer.EndPacket();
            return buffer;
        }

        // 二进制数据转换结构
        public MsgBase ReadByBinary(Buffer buffer)
        {
            MsgBase msg = Create();
            BinaryReader binaryReader = buffer.BeginReading();
            msg.ReadByBinary(binaryReader);
            return msg;
        }
    }

    public class Callback<T> : CallbackBase where T : MsgBase, new()
    {
        public delegate void OnCallback(T msg);
        public Callback(OnCallback callback)
        {
            mCallback = callback;
        }

        OnCallback mCallback;

        // 事件回调
        public override void OnEvent(MsgBase obj)
        {
            mCallback((T)obj);
        }

        protected override MsgBase Create()
        {
            return new T();
        }
    }
}